package com.techchat.backend.network;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Component;
import jakarta.annotation.PostConstruct; // 替换 javax.annotation
//import javax.annotation.PostConstruct;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.nio.charset.StandardCharsets;

@Component
public class UdpServer {
    private static final Logger logger = LoggerFactory.getLogger(UdpServer.class);
    private static final int UDP_PORT = 9876;

    private final SimpMessagingTemplate messagingTemplate;

    @Autowired
    public UdpServer(SimpMessagingTemplate messagingTemplate) {
        this.messagingTemplate = messagingTemplate;
    }

    @PostConstruct
    public void start() {
        new Thread(() -> {
            try (DatagramSocket socket = new DatagramSocket(UDP_PORT)) {
                logger.info("UDP Server started on port {}", UDP_PORT);

                byte[] buffer = new byte[1024];
                while (true) {
                    DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
                    socket.receive(packet);

                    String message = new String(
                            packet.getData(),
                            0,
                            packet.getLength(),
                            StandardCharsets.UTF_8
                    );

                    logger.info("UDP Received from {}: {}", packet.getAddress(), message);

                    // 转发到WebSocket客户端
                    messagingTemplate.convertAndSend("/topic/public", message);
                }
            } catch (Exception e) {
                logger.error("UDP Server error", e);
            }
        }).start();
    }
}
